package com.jj.service.user;

import com.jj.aop.annotation.RPC;
import com.jj.config.Constants;
import com.jj.core.client.impl.ClientImpl;
import com.jj.core.rpc.RPCHandler;
import com.jj.core.rpc.RPCManager;
import com.jj.message.battle.UserMessage;
import com.jj.net.Context;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
public class GenericRPCProxy extends RPCHandler {
    private static Logger logger = LoggerFactory.getLogger(GenericRPCProxy.class);

    @RPC(generic = true)
    public UserMessage call(String command){
        logger.debug("call command:{}", command);
        String[] cmdArgs = command.split(",");
        Integer rpcId = Integer.parseInt(cmdArgs[0]);
        try {
            Context context = getContext();
            Object retvalue = rpcManager.callGeneric(rpcId, cmdArgs, 1, context);
            if(retvalue != null && retvalue instanceof UserMessage){
                ((UserMessage) retvalue).setMsgID((short) 0);
                return (UserMessage) retvalue;
            }else{
                Long uid = (Long) context.getAttr(Constants.USER_ID_KEY);
                ClientImpl client = (ClientImpl) clientManager.get(uid);
                {
                    UserMessage userMessage = null;
                    if(retvalue != null){
                        userMessage = clientManager.msg().onGenericCall(retvalue);
                    }else{
                        userMessage = clientManager.msg().onGenericCall("");
                    }
                    //client.send(userMessage);
                    userMessage.setMsgID((short) 0);
                    return userMessage;
                }
            }
        } catch (RPCManager.RPCNotFoundException e) {
            logger.error("exception", e);
        } catch (RPCManager.RPCException e) {
            logger.error("exception", e);
        }
        return null;
    }
}
